package com.dkm.service.impl;

import java.util.Date;
import java.util.List;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dkm.entity.Message;
import com.dkm.entity.Users;
import com.dkm.repository.MessageRepository;
import com.dkm.repository.UsersRepository;
import com.dkm.service.MessageService;
import com.dkm.util.ResultUtil;
import com.dkm.websocket.CommunicateWebSocket;

@Service
public class MessageServiceImpl implements MessageService {

	//注入消息持久层
	@Autowired
	private MessageRepository messageRepository;
	//注入用户持久层
	@Autowired
	private UsersRepository usersRepository;
	
	//注入websocket
	@Autowired
	private CommunicateWebSocket communicateWebSocket;
	
	@Override
	public List<Users> getUserMessages(String cur_user_id,List<Users> users) {
		//遍历所有用户
//		Iterator<TmPositionJob> iterator = lists.iterator();
//        while(iterator.hasNext()){
//            TmPositionJob o = iterator.next();
//            if("终止".equalsIgnoreCase(o.getOperName()) || "解挂".equalsIgnoreCase(o.getOperName()))
//                iterator.remove();   //注意这个地方
//        }
		
		for (int i=0;i<users.size();i++) {
			Users user=users.get(i);
			//如果是当前用户移除
			if(user.getUser_id().equals(cur_user_id)) {
				users.remove(user);
				i--;
				//跳过本次循环
				continue;
			}
			//根据发送人和接收人获取最新的10条消息
			List<Message> messages=messageRepository.getMessagesBySender_idAndReceiver_id(cur_user_id, user.getUser_id());
			
			//如果消息不为空
			if(messages!=null&&messages.size()>0) {
				//设置给遍历的用户
				user.setMessages(messages);
			}
		}
		
		//返回带消息集合的用户
		return users;
	}
	
	@Override
	public ResultUtil addMessage(String sender_id, String content, String receiver_id) {
		
		//创建消息对象
		Message message=new Message();
		
		//发送人
		Users sender=usersRepository.findById(sender_id).get();
		if(sender==null) {
			return new ResultUtil(-1, "发送失败！发送人数据异常", null);
		}
		message.setSender(sender);
		
		//设置消息内容
		message.setContent(content);
		//发送时间
		message.setSendTime(new Date());
		//消息状态
		message.setStatus("未读");
		
		//接收人存在
		if(!"0".equals(receiver_id)) {
			Users receiver=usersRepository.findById(receiver_id).get();
			if(receiver==null) {
				return new ResultUtil(-1, "发送失败！接收人不存在", null);
			}
			//设置接收人
			message.setReceiver(receiver);
			//消息类型
			message.setMtype("普通消息");
			
			//content=sender_id+"|"+content+"|"+receiver_id;
			//发给指定用户
			//communicateWebSocket.sendToUser(message);
		}else {
			message.setMtype("广播消息");
			//content=sender_id+"|"+content;
			//发给所有用户（广播）
			//communicateWebSocket.sendAll(message);
		}
		
		//添加消息
		Message m1=messageRepository.saveAndFlush(message);
		if(m1!=null) {
			return new ResultUtil(0, "发送成功！", m1);
		}
		return new ResultUtil(-1, "发送失败！", null);
	}

}
